import { Low } from 'lowdb'
import { JSONFile } from 'lowdb/node'
import { join, dirname } from 'path'
import { fileURLToPath } from 'url'
import fs from 'fs'

// 获取当前目录路径
const __dirname = dirname(fileURLToPath(import.meta.url))

// 确保data目录存在
const dataDir = join(__dirname, '../data')
if (!fs.existsSync(dataDir)) {
  fs.mkdirSync(dataDir)
}

// 数据库文件路径
const file = join(dataDir, 'tempQuestions.json')

// 初始化数据库
const adapter = new JSONFile(file)
const db = new Low(adapter, { questions: [] })

// 初始化数据结构
async function initDB() {
  await db.read()
  if (!db.data) {
    db.data = { questions: [] }
    await db.write()
  }
}

// 添加题目到临时题库
async function addQuestions(newQuestions) {
  await db.read()
  db.data.questions.push(...newQuestions)
  await db.write()
  return db.data.questions
}

// 获取临时题库
async function getQuestions() {
  await db.read()
  return db.data.questions
}

// 清空临时题库
async function clearQuestions() {
  await db.read()
  db.data.questions = []
  await db.write()
}

export {
  initDB,
  addQuestions,
  getQuestions,
  clearQuestions
}
